package com.etymgiko.lyricscollectionseam.session;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.framework.EntityHome;

import com.etymgiko.lyricscollectionseam.entity.Artist;
import com.etymgiko.lyricscollectionseam.entity.Song;

/**
 * @author Ivan Holub
 */
@Name("artistHome")
@Scope(ScopeType.EVENT)
public class ArtistHome extends EntityHome<Artist> {

	@In(create = true)
	private ArtistManager artistManager;
	
	public void setArtistId(Long id) {
		setId(id);
	}

	public Long getArtistId() {
		return (Long) getId();
	}
	
	public String getArtistName() {
		if (artistNameParam != null) {
			return artistNameParam;
		}
		return getInstance() == null ? null : getInstance().getName();
	}
	
	private String artistNameParam;
	
	public void setArtistName(String artistName) {
		this.artistNameParam = artistName;
	}

	@Override
	protected Artist createInstance() {
		Artist artist = new Artist();
		return artist;
	}

	public List<Song> getSongs() {
		return getInstance() == null ? null : getInstance().getSongs();
	}
	
	public String save() {
		boolean isSuccess = false;
		
		if (isManaged()) {
			if (getInstance().getName().equals(artistNameParam)) {
				isSuccess = true;
			}
		}
		if (!isSuccess) {
			if (artistManager.findArtist(artistNameParam) != null) {
	            FacesMessage message =
	                new FacesMessage("Artist with such name already exists");
	            FacesContext.getCurrentInstance().addMessage("artistForm:artistName", message);
	            return null;
			}
		}
		
		getInstance().setName(artistNameParam);
		
		if (isManaged()) {
			update();
		} else {
			persist();
		}
		
		return "success";
	}
}
